//
//  AppDelegate.m
//  chequanbao_ios
//
//  Created by pro on 17/5/6.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "AppDelegate.h"
#import "ByUILoginVC.h"

#import "ByUIAppGuideVC.h"
@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 地图配置
    self.mapManager = [[BMKMapManager alloc] init];
    BOOL ret = [_mapManager start:@"uhVyh2hPPY99Sq11t1fV9pSvGpCBgSOz"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    // 友盟配置
    [self UMessageInitWithOptions:launchOptions];
    [self UMAnalyicasInit];

    [NSThread sleepForTimeInterval:3.0];//设置启动页面时间

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window setBackgroundColor:[UIColor whiteColor]];
    [self.window makeKeyAndVisible];
    self.window.rootViewController = [[ByTabBarController alloc] init];

    if([ByUIAppGuideVC needShowGuide]) {
        self.window.rootViewController = [ByUIAppGuideVC appGuideVCWithImageNames:nil videoURL:nil enterBlock:^{
            [self enter:YES];
        } configuration:^(UIButton *enterButton, UIButton *timerButton) {
            
        } timerDuration:3];
    } else {
        [self enter:NO];
    }
    // 判断是否需要登录
//    if (BY_USER) {
//       [self needLogin:NO];
//    }
//    else{
//      [self needLogin:YES];
//    }
 
    // 微信初始化
    [self WXApiInit];
    
    // 获取app配置
    [BY_CONFIG setGlobalConfig];
    
    [self scrollAppearanceFit];
    
    return YES;
}
- (void)enter:(BOOL)needTransition {
    
    self.window.rootViewController = [[ByTabBarController alloc] init];
    if (needTransition) {
        [self.window.layer transitionWithAnimType:TransitionAnimTypeFade subType:TransitionSubtypesFromRight curve:TransitionCurveDefault duration:1.5f];
    }
}

#pragma mark - 基于ios11的全局适配
- (void)scrollAppearanceFit {
    
    UITableView.appearance.tableFooterView = UIView.new;
    
    if (@available(ios 11.0,*)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        UITableView.appearance.estimatedRowHeight = 0;
        UITableView.appearance.estimatedSectionFooterHeight = 0;
        UITableView.appearance.estimatedSectionHeaderHeight = 0;
    }
    
    [UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]].translucent = false;
    [[UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]] setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithWhite:0.98 alpha:1]] forBarMetrics:UIBarMetricsDefault];
}


#pragma mark --
//- (void)needLogin:(BOOL)needLogin{
//    if (needLogin) {
//        ByUILoginVC *vc = [[ByUILoginVC alloc] init];
//        self.window.rootViewController = vc;
//    }
//    else{
//        ByTabBarController *vc = [[ByTabBarController alloc] init];
//        self.window.rootViewController = vc;
//    }
//}

#pragma mark - 友盟
- (void)UMessageInitWithOptions:(NSDictionary *)launchOptions {
    
    [UMessage startWithAppkey:UMENG_APPKEY launchOptions:launchOptions];
    
    [UMessage registerForRemoteNotifications];
    
    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    UNAuthorizationOptions types10 = UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            //这里可以添加一些自己的逻辑
        } else {
            //点击不允许
            //这里可以添加一些自己的逻辑
        }
    }];
    
    
    [UMessage setLogEnabled:YES];
}
- (void)UMAnalyicasInit {
    UMConfigInstance.appKey = UMENG_APPKEY;
    UMConfigInstance.channelId = @""; // channelId为nil或@""时，默认会被当作@"App Store"渠道
    [MobClick startWithConfigure:UMConfigInstance];
    //
    [MobClick setAppVersion:APP_VERSION]; // 以App打包时的Build号作为应用程序的版本标识
    //
    //    /** 打开调试模式，打开调试模式后，可以在logcat中查看用户的数据是否成功发送到友盟服务器，以及集成过程中的出错原因等，友盟相关log的tag是MobclickAgent */
    [MobClick setLogEnabled:YES];
    
}


#pragma mark - 链接回调处理

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]){
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            /**
             *  发起国际支付宝请求
             *  成功与失败的传入值：NSDictionary 中的key如下
             *  resultStatus = 返回的结果 编码
             *  success = 成功时会有值,失败时null
             *  memo = 错误时，返回的错误信息
             *  result = 返回的支付相关的信息，一般用不到
             *  sign = 签名串，暂时不用管
             */
            
            NSString * resultStatus =[resultDic valueForKey:@"resultStatus"];
            NSString * memo =[resultDic valueForKey:@"memo"];
            
            /*
             9000 表示支付成功
             8000 正在处理中
             4000 订单支付失败
             6001 用户中途取消
             6002 网络连接出错
             */
            
            if ([resultStatus isEqualToString:@"9000"] ) {
                NSLog(@" 张占彬 支付宝支付成功");
                [[NSNotificationCenter defaultCenter] postNotificationName:@"aliPaySuccess" object:nil userInfo:resultDic];
            } else {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"aliPayFailure" object:nil userInfo:resultDic];
                NSLog(@"aliPayFailure = %@", memo);
                [ByCoreToolAlert showFailureWithText:memo];
            }
            
        }];
        return YES;
    }else{
        return [WXApi handleOpenURL:url delegate:self] ;
    }
    
}


#pragma mark -- 微信
- (void)WXApiInit {
    [WXApi registerApp:WEIXIN_APPID];
}


#pragma mark - WXApiDelegate
- (void)onReq:(BaseReq *)req{
    DLog(@"微信onReq");
}
- (void)onResp:(BaseResp *)resp{
    DLog(@"微信onResp");
    
    if (resp == nil) {
        NSLog(@"不能为空!");
        return;
    }
     // 支付
    if ([resp isKindOfClass:[PayResp class]]){
        PayResp *response = (PayResp *)resp;
        switch(response.errCode) {
            case
            WXSuccess:
                //服务器端查询支付通知或查询API返回的结果再提示成功
                NSLog(@"支付成功");
                [[NSNotificationCenter defaultCenter] postNotificationName:@"wechatPaySuccess" object:self userInfo:nil];
                break;
            default:
                NSLog(@"支付失败，retcode=%d", resp.errCode);
                [[NSNotificationCenter defaultCenter] postNotificationName:@"wechatPayFailure" object:self userInfo:@{@"errorInfo":response}];
                break;
        }
    }
    
    // 分享
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        NSString *strMsg;
        switch (resp.errCode) {
            case 0:
                strMsg = @"分享成功！";
                break;
            case -2:
                strMsg = @"用户中途取消！";
                break;
            case -5:
                strMsg = @"网络超时！";
                break;
            case -1:
            case -4:
                strMsg = @"其他错误！";
                break;
            case -3:
                strMsg = @"发送失败！";
                break;
            default:
                break;
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strMsg message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}
#pragma mark - 链接回调处理
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL isSuc = [WXApi handleOpenURL:url delegate:self];
    NSLog(@"url %@ isSuc %d",url,isSuc == YES ? 1 : 0);
    return  isSuc;
}

#pragma mark --
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
